package com.moonshine.comic;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;





import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class MoonShineComicActivity extends Activity {
    /** Called when the activity is first created. */
	
	private static String imageName;
	 private final String website = "http://www.moonshinecomic.com/pkgs/marvin/dl.phtml/comic/";  //grab from this site, with comic number +
	 private final String webcheck = "http://moonshinecomic.com/home.phtml/";
	static int comicNumber =70;
	static int newestComic;
	static String currentComic;
	static String websiteGrab;
	static String newGrab;
	private File imageFile;
	Context context;
	SharedPreferences prefs;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        context = this;
        ImageView mainImage = (ImageView) findViewById(R.id.current_comic);
        ImageButton next = (ImageButton) findViewById(R.id.iconForward);
        ImageButton back = (ImageButton) findViewById(R.id.iconBack);
        ImageButton start = (ImageButton) findViewById(R.id.iconAllBack);
        ImageButton end = (ImageButton) findViewById(R.id.iconAllForward);

        currentComic = ""+comicNumber;
        websiteGrab = website + "" + comicNumber;
        //newGrab = website + "" + newestComic;
        
        
        
        newestComic = prefs.getInt("newestComic", 1);
        
        
        
        
        next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				int tries = 0;
				comicNumber++;
				currentComic = ""+comicNumber;
		        websiteGrab = website + "" + comicNumber;
		        
		        while(downloadImage(getApplicationContext(), websiteGrab)==null && tries < 3){
		    		Log.d("MoonshineMain", "Download of image failed");
		    		comicNumber++;
		    		currentComic = ""+comicNumber;
			        websiteGrab = website + "" + comicNumber;
			        
			        if(newestComic < comicNumber){
			        	newestComic = comicNumber;
			        	prefs.edit().putInt("newestComic", newestComic).commit();
			        	Toast.makeText(context, "Newest Comic is ", newestComic).show();
			        }
			        tries++;
			        
			        
		    	}
		        if(tries==3){
		        	comicNumber = comicNumber - 4;
		        	currentComic = ""+comicNumber;
			        websiteGrab = website + "" + comicNumber;
			        if(newestComic > comicNumber){
			        	newestComic = comicNumber;
			        	prefs.edit().putInt("newestComic", comicNumber).commit();
			        }
			        
			        
		        	Log.d("MoonshineMain", "Whoops we went too far Scotty, going back to last comic: "+ websiteGrab);
		        }
		        
		        Log.d("MoonshineMain", "Current comic: "+ websiteGrab);
		        
		        Refresh(context);
			}
        });
        
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (comicNumber >= 2) {
					int tries = 0;
					comicNumber--;
					currentComic = "" + comicNumber;
					websiteGrab = website + "" + comicNumber;

					while (downloadImage(getApplicationContext(), websiteGrab) == null && tries < 3) {
						Log.d("MoonshineMain", "Download of image failed");
						comicNumber--;
						currentComic = "" + comicNumber;
						websiteGrab = website + "" + comicNumber;
						tries++;
					}

					Log.d("MoonshineMain", "Current comic: " + websiteGrab);

					Refresh(context);
				}else{
					Log.d("MoonshineMain", "Back button failed comic number "+comicNumber);
				}
			}
		});
        
		end.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
					int tries = 0;
					comicNumber = newestComic;
					
					
					
					currentComic = "" + comicNumber;
					websiteGrab = website + "" + comicNumber;

					while (downloadImage(getApplicationContext(), websiteGrab) == null && tries < 3) {
						Log.d("MoonshineMain", "Download of image failed");
						comicNumber--;
						currentComic = "" + comicNumber;
						websiteGrab = website + "" + comicNumber;
						tries++;
					}

					Log.d("MoonshineMain", "Current comic: " + websiteGrab);

					Refresh(context);
				
			}
		});
        
        
        
        
        
        
        
        
        
        
        
        //precache. 
        //saveImageFromUrl(this, websiteGrab, currentComic);
        Log.d("MoonshineMain", "downloadImage " + websiteGrab);
     
        
      
//        mainImage.setImageResource(R.drawable.comic36);
        
        
        ReadFile("1");  
        mainImage.setImageDrawable(downloadImage(this, websiteGrab));
    }
    
    
    public void Refresh(Context c){
    	ImageView mainImage = (ImageView) findViewById(R.id.current_comic);
    	
    	
    	 mainImage.setImageDrawable(downloadImage(c.getApplicationContext(), websiteGrab));
    	 
    }
    
    
    public static Drawable downloadImage(Context ctx, String url) {
		try {
			InputStream is = (InputStream) fetch(url);
			Drawable d = Drawable.createFromStream(new FlushedInputStream(is), "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
    
    public static Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		
		
		
		return content;
	}
    
    
    
    
    public static class FlushedInputStream extends FilterInputStream {
	    public FlushedInputStream(InputStream inputStream) {
	        super(inputStream);
	    }

	    @Override
	    public long skip(long n) throws IOException {
	        long totalBytesSkipped = 0L;
	        while (totalBytesSkipped < n) {
	            long bytesSkipped = in.skip(n - totalBytesSkipped);
	            if (bytesSkipped == 0L) {
	                  int curByte = read();
	                  if (curByte < 0) {
	                      break;  // we reached EOF
	                  } else {
	                      bytesSkipped = 1; // we read one byte
	                  }
	           }
	            totalBytesSkipped += bytesSkipped;
	        }
	        return totalBytesSkipped;
	    }
	}
    
    public static void saveImageFromUrl(Context c, String address, String saveFilename) {
		try {
			int count = 0;
			Log.d("ImageOperations", "saveImageFromUrl " + address + " to filename " + saveFilename);
			
			imageName = saveFilename;
			
			URL url = new URL(address);
			Object content = url.getContent();
			
			while(content==null && count<20){
				content = url.getContent();
				count++;
				Log.d("ImageOperations", "url.getContent() try "+count);
			}
			count=0;
			if (content!=null){
				
				FlushedInputStream is = new FlushedInputStream((InputStream) content);
				
				while(is==null && count<20 ){
					is = new FlushedInputStream((InputStream) content);
					count++;
					Log.d("ImageOperations", "input stream try "+count);
				}
				if(is!=null){

					File newFile = new File(c.getDir("images", Context.MODE_PRIVATE).getAbsolutePath(),saveFilename);

					FileOutputStream fos = new FileOutputStream(newFile);


					byte buf[]=new byte[1024*4];
					int len;
					while((len=is.read(buf))>0)
						fos.write(buf,0,len);

					fos.flush();
					fos.close();
				}else{
					Log.d("ImageOperations", "saveImageFromUrl " + address + " to filename " + saveFilename + "FAILED");
				}
			}else{
				Log.d("ImageOperations", "url.getContent() failed and is null");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//To signify that the file has finished downloading
		imageName = null;
	}	
        
        
        public Bitmap ReadFile(String fileName){
        	
        	
        	
        	
        	
        	
        	
        	imageFile = new File(this.getDir ("images", Context.MODE_PRIVATE).getAbsolutePath(),fileName);
        	
        	
        	Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        	
        	return myBitmap;
//        	
//        	String FILENAME = "hello_file";
//        	String string = "hello world!";
//
//        	FileInputStream fos;
//        	
//        	
//        	
//			try {
//				fos = openFileInput(fileName);
//				
//				fos.read();
//	        	fos.close();
//				
//				
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//			
			
        
        	
        }
        
    
}